package abel.wlmr.model.unit;

import java.util.ArrayList;
import java.util.List;

import abel.wlmr.model.WlmrBasePart;
import abel.wlmr.model.WlmrBaseUnit;
import abel.wlmr.model.WlmrDefaultUnit;
import abel.wlmr.model.WlmrException;
import abel.wlmr.model.type.DataIdBody;
import io.netty.buffer.ByteBuf;

public class AfnThirdDownPart extends WlmrBasePart {

    public static final short F_IMPORTANT_EVENT = 1;
    public static final short F_NORMAL_EVENT = 2;

    public AfnThirdDownPart() {
        super();
    }

    public AfnThirdDownPart(short guessedLen) {
        super(guessedLen);
    }

    @Override
    public int parseBuf(ByteBuf buf) throws WlmrException {
        id = new DataIdBody();
        id.parseBuf(buf);

        short len = (short) (getGuessedLength() - 4);

        // same DA.
        List<WlmrBaseUnit> bodys = new ArrayList<>();
        unitList.add(bodys);

        // DT list for one DA.
        for (short dt : id.getDt().typeList()) {

            DataIdBody outerId = new DataIdBody();
            outerId.getDt().setTypeList(dt);

            switch (dt) {
            case F_IMPORTANT_EVENT:
            case F_NORMAL_EVENT:

            {
                AfnThirdF1_2DownUnit body = new AfnThirdF1_2DownUnit(len);
                body.setOuterId(outerId);

                int plen = body.parseBuf(buf);
                if (plen < 0) {
                    throw new WlmrException("not enough bytes but length is assigned.");
                }

                len -= plen;
                bodys.add(body);

                break;
            }

            default:

            {
                WlmrBaseUnit body = new WlmrDefaultUnit(len);
                body.setOuterId(outerId);

                len -= body.parseBuf(buf);
                bodys.add(body);

                break;
            }
            }
        }

        return getGuessedLength() - len;
    }
}
